<template>
  <div class="UploadFile-container">
    <template v-if="JSON.stringify(fileList)!='{}'">
      <transition-group
        class="el-upload-list el-upload-list--picture-card"
        tag="ul"
        name="el-list"
      >
        <li
          class="el-upload-list__item is-success"
          v-for="(file, index) in fileList"
          :key="index + 'ccc'"
        >
          <el-image
            :src="file.url"
            class="el-upload-list__item-thumbnail"
            :preview-src-list="getImgList(fileList)"
            :z-index="10000"
            :ref="'image' + index"
          >
          </el-image>
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(index)"
            >
              <i class="el-icon-zoom-in"></i>
            </span>
            <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(index)"
            >
              <i class="el-icon-delete"></i>
            </span>
            <span
              class="el-upload-list__item-delete"
              @click="downLoadImg(file)"
            >
              <i class="el-icon-download"></i>
            </span>
          </span>
        </li>
      </transition-group>
    </template>
    <el-upload
      v-if="!disabled && limitShow"
      action=""
      :headers="uploadHeaders"
      :file-list="fileList"
      :multiple="limit !== 1"
      :show-file-list="false"
      accept="image/*"
      :http-request="uploadFile"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :disabled="disabled"
      ref="upload"
      list-type="picture-card"
      :limit="limit"
      class="upload-btn"
      :auto-upload="false"
    >
      <i class="el-icon-plus"></i>
      <div slot="tip" class="el-upload__tip" v-show="showTip">
        只能上传不超过{{ fileSize }}{{ sizeUnit }}的{{ accept }}图片
      </div>
    </el-upload>
  </div>
</template>

<script>
import request from "@/utils/request";
const units = {
  KB: 1024,
  MB: 1024 * 1024,
  GB: 1024 * 1024 * 1024
};
export default {
  name: "UploadImg",
  props: {
    value: {
      required: true,
      default: () => []
    },
    type: {
      type: String,
      default: "annexpic"
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showTip: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 0
    },
    accept: {
      type: String,
      // default: "image/*",
      default: ""
    },
    sizeUnit: {
      type: String,
      default: "MB"
    },
    fileSize: {
      default: 2
    }
  },
  data() {
    return {
      fileData: "",
      fileList: this.value,
      uploadData: {
        fieldData: {
          id: "" // 机构id,
        }
      },
      limitShow: 1, // 代替fileList 配合limit判断length
      baseUrl: `${this.define.comUploadUrl}/upload`,
      uploadHeaders: { Authorization: this.$store.getters.token }
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (typeof val === "string") {
          this.fileList = JSON.parse(val);
          this.limit == this.fileList.length && (this.limitShow = 0);
        } else {
          this.fileList = val;
          this.limit == this.fileList.length && (this.limitShow = 0);
        }
      }
    }
  },
  methods: {
    //监控上传文件列表
    handleChange(file, fileList) {
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find(f => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
      clearTimeout(this.myTime);
      this.myTime = setTimeout(() => {
        this.submit();
      }, 100);
    },
    // 上传文件
    uploadFile(file) {
      this.fileData.append("file", file.file); // append增加数据
    },
    submit() {
      if (!this.fileList.length) {
        this.$message({
          message: "请先选择文件",
          type: "warning"
        });
      } else {
        const unitNum = units[this.sizeUnit];
        let currentUpload = this.fileList.filter(item => item.size);
        const isLt100M = currentUpload.every(
          file => file.size / unitNum < this.fileSize
        );
        if (!isLt100M) {
          this.$message.error(
            `请检查，上传文件大小不能超过${this.fileSize}MB!`
          );
          this.fileList.forEach((item, index) => {
            if (item.size / 1024 / 1024 > this.fileSize) {
              this.fileList.splice(index, 1);
            }
          });
        } else {
          this.fileData = "";
          this.fileData = new FormData(); // new formData对象
          this.$refs.upload.submit(); // 提交调用uploadFile函数
          request({ 
            url: this.baseUrl,
            method: "post",
            data: this.fileData,
            headers: { Authorization: this.$store.getters.token }
          }).then(res => {
            if (res.code == 200) {
              // this.$message({
              //   message: "上传成功",
              //   type: "success",
              //   duration: 1000,
              //   onClose: () => (this.isUpload = true),
              // });
              this.fileList.forEach((item, index) => {
                res.data.forEach(item1 => {
                  if (item.name == item1.name) {
                    this.$set(this.fileList, index, {
                      name: item1.name,
                      fileId: item1.fileId,
                      url: item1.ossAddress
                    });
                  }
                });
              });
              this.$emit("input", JSON.stringify(this.fileList));
            } else {
              this.$message({
                message: res.data.desc,
                type: "error"
              });
            }
          });
        }
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多可以上传${this.limit}张图片`);
    },
    handlePictureCardPreview(index) {
      this.$refs["image" + index][0].clickHandler();
    },
    handleRemove(index) {
      // 如果limit1 删除时给他改成0
      this.limitShow = 0;
      this.show = true;
      this.fileList.splice(index, 1);
      this.limit !== this.fileList.length && (this.limitShow = 1);
      this.$emit("input", JSON.stringify(this.fileList));
    },
    getImgList(list) {
      const newList = list.map(o => o.url);
      return newList;
    },
    downLoadImg(file) {
      if (!file.fileId) return;
      window.location.href = file.url;
    }
  }
};
</script>
<style lang="scss" scoped>
>>> .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}
>>> .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 120px;
}
.upload-btn {
  display: inline-block;
}
.el-upload-list__item-thumbnail {
  width: 180px;
  height: 210px;
}
</style>
